import os
import requests
from datetime import datetime, timedelta

# ===== 配置 =====
API_KEY = "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"
PROXY = {
    "http": "http://127.0.0.1:7890",
    "https": "http://127.0.0.1:7890"
}
# ================

# OpenAI 计费接口
BASE_URL = "https://api.openai.com/v1"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}

def get_billing_info():
    # 先查账单开始和结束时间（默认查过去90天到未来1天）
    today = datetime.now()
    start_date = (today - timedelta(days=90)).strftime("%Y-%m-%d")
    end_date = (today + timedelta(days=1)).strftime("%Y-%m-%d")

    # 获取总额度（subscription info）
    sub_url = "https://api.openai.com/v1/dashboard/billing/subscription"
    sub_resp = requests.get(sub_url, headers=HEADERS, proxies=PROXY)
    sub_data = sub_resp.json()
    total_granted = sub_data.get("hard_limit_usd", 0)  # 总额度（美元）

    # 获取已用额度（usage info）
    usage_url = f"https://api.openai.com/v1/dashboard/billing/usage?start_date={start_date}&end_date={end_date}"
    usage_resp = requests.get(usage_url, headers=HEADERS, proxies=PROXY)
    usage_data = usage_resp.json()
    total_used = usage_data.get("total_usage", 0) / 100  # API 返回的是美分

    return total_granted, total_used

if __name__ == "__main__":
    try:
        granted, used = get_billing_info()
        remaining = granted - used
        print(f"总额度: ${granted:.2f}")
        print(f"已用额度: ${used:.2f}")
        print(f"剩余额度: ${remaining:.2f}")
        if remaining <= 0:
            print("⚠️ 额度已用完或账号没有充值")
    except Exception as e:
        print("查询失败:", e)
